package com.madixin.madichat.ui.feature.chat

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.madixin.madichat.model.ChatSession
import com.madixin.madichat.model.Message
import com.madixin.madichat.repository.ChatSessionRepository
import com.madixin.madichat.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

    // 添加ChatSessionRepository作为依赖
    class ChatViewModel(
        private val preferencesManager: PreferencesManager,
        private val chatSessionRepository: ChatSessionRepository = ChatSessionRepository(preferencesManager)
    ) : ViewModel() {

    private val _sessions = MutableStateFlow<List<ChatSession>>(emptyList())
    val sessions: StateFlow<List<ChatSession>> = _sessions

    private val _currentSessionId = MutableStateFlow<String?>(null)
    val currentSessionId: StateFlow<String?> = _currentSessionId

    private val _messages = MutableStateFlow<List<Message>>(emptyList())
    val messages: StateFlow<List<Message>> = _messages

    private val _inputText = MutableStateFlow("")
    val inputText: StateFlow<String> = _inputText

    private val _isDrawerOpen = MutableStateFlow(false)
    val isDrawerOpen: StateFlow<Boolean> = _isDrawerOpen

    private val _showEditDialog = MutableStateFlow(false)
    val showEditDialog: StateFlow<Boolean> = _showEditDialog

    private val _showDeleteDialog = MutableStateFlow(false)
    val showDeleteDialog: StateFlow<Boolean> = _showDeleteDialog

    private val _sessionToEdit = MutableStateFlow<ChatSession?>(null)
    val sessionToEdit: StateFlow<ChatSession?> = _sessionToEdit

    private val _newSessionTitle = MutableStateFlow("")
    val newSessionTitle: StateFlow<String> = _newSessionTitle

    // 添加错误消息状态流
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage

    init {
        createNewChat()
        // 加载会话列表
        loadSessions()
    }

    private fun loadSessions() {
        viewModelScope.launch {
            try {
                val result = chatSessionRepository.getChatSessions()
                if (result.isSuccess) {
                    _sessions.value = result.getOrNull() ?: emptyList()
                } else {
                    // 处理错误情况，添加错误日志和提示
                    val errorMsg = result.exceptionOrNull()?.message ?: "获取会话列表失败"
                    android.util.Log.e("ChatViewModel", "加载会话列表失败: $errorMsg")
                    _errorMessage.value = "加载会话列表失败: $errorMsg"
                    // 如果API调用失败，可以考虑使用空列表或缓存数据
                    _sessions.value = emptyList()
                }
            } catch (e: Exception) {
                // 处理异常情况，添加异常日志和提示
                android.util.Log.e("ChatViewModel", "加载会话列表异常", e)
                _errorMessage.value = "加载会话列表失败: ${e.message ?: "未知错误"}"
                _sessions.value = emptyList()
            }
        }
    }

    private fun loadMessages(sessionId: String) {
        viewModelScope.launch {
            try {
                val result = chatSessionRepository.getSessionMessages(sessionId)
                if (result.isSuccess) {
                    _messages.value = result.getOrNull() ?: emptyList()
                } else {
                    // 处理错误情况，添加错误日志和提示
                    val errorMsg = result.exceptionOrNull()?.message ?: "获取消息列表失败"
                    android.util.Log.e("ChatViewModel", "加载消息列表失败: $errorMsg")
                    _errorMessage.value = "加载消息列表失败: $errorMsg"
                    // 如果API调用失败，可以考虑使用空列表或缓存数据
                    _messages.value = emptyList()
                }
            } catch (e: Exception) {
                // 处理异常情况，添加异常日志和提示
                android.util.Log.e("ChatViewModel", "加载消息列表异常", e)
                _errorMessage.value = "加载消息列表失败: ${e.message ?: "未知错误"}"
                _messages.value = emptyList()
            }
        }
    }

    fun createNewChat() {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        val newSessionId = UUID.randomUUID().toString()
        val newSession = ChatSession(
            id = newSessionId,
            title = "新对话",
            lastUpdateTime = dateFormat.format(Date())
        )

        _sessions.value = listOf(newSession) + _sessions.value
        _currentSessionId.value = newSessionId
        
        // 创建AI的欢迎消息
        val welcomeMessage = Message(
            id = UUID.randomUUID().toString(),
            content = "Hi~ 我是MadiChat 你身边的智能助手",
            timestamp = timeFormat.format(Date()),
            isUser = false
        )
        
        // 设置消息列表，包含欢迎消息
        _messages.value = listOf(welcomeMessage)
    }

    fun updateInputText(text: String) {
        _inputText.value = text
    }

    fun sendMessage() {
        if (_inputText.value.isBlank() || _currentSessionId.value == null) return

        val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        val userMessage = Message(
            id = UUID.randomUUID().toString(),
            content = _inputText.value,
            timestamp = timeFormat.format(Date()),
            isUser = true
        )
    
        // 添加用户消息到列表
        _messages.value = _messages.value + userMessage
        
        // 检查是否是新对话的首次聊天
        val isFirstChat = _messages.value.size == 1 || (_messages.value.size == 2 && _messages.value[0].isUser == false && _messages.value[0].content == "Hi~ 我是MadiChat 你身边的智能助手")
        
        // 清空输入框
        val userInput = _inputText.value
        _inputText.value = ""
        
        // 如果是新对话的首次聊天，直接更新本地会话列表中的标题
        if (isFirstChat) {
            val newTitle = if (userInput.length > 10) userInput.substring(0, 10) else userInput
            val currentSessionId = _currentSessionId.value!!
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            
            // 检查当前会话ID是否存在于会话列表中
            val sessionExists = _sessions.value.any { it.id == currentSessionId }
            
            if (sessionExists) {
                // 如果会话已存在，只更新标题
                _sessions.value = _sessions.value.map { session ->
                    if (session.id == currentSessionId) {
                        session.copy(title = newTitle)
                    } else {
                        session
                    }
                }
            } else {
                // 如果会话不存在，创建新会话并添加到列表首位
                val newSession = ChatSession(
                    id = currentSessionId,
                    title = newTitle,
                    lastUpdateTime = dateFormat.format(Date())
                )
                _sessions.value = listOf(newSession) + _sessions.value
            }
        }
        
        // 创建一个临时的AI消息，显示思考状态
        val tempAiMessageId = UUID.randomUUID().toString()
        val tempAiMessage = Message(
            id = tempAiMessageId,
            content = "",
            timestamp = timeFormat.format(Date()),
            isUser = false,
            thinkingProcess = "正在思考您的问题..."
        )
        
        // 添加临时AI消息到列表
        _messages.value = _messages.value + tempAiMessage
        
        // 调用API发送消息并处理流式响应
        viewModelScope.launch {
            try {
                var aiContent = ""
                var latestThinking = "正在思考您的问题..."
                var finalMessageId = tempAiMessageId
                
                // 更新临时消息的思考过程
                fun updateThinkingMessage() {
                    val currentMessages = _messages.value.toMutableList()
                    val index = currentMessages.indexOfFirst { it.id == tempAiMessageId }
                    if (index != -1) {
                        currentMessages[index] = currentMessages[index].copy(
                            content = aiContent,
                            thinkingProcess = latestThinking
                        )
                        _messages.value = currentMessages
                    }
                }
                
                // 发送消息并处理流式响应
                chatSessionRepository.sendMessage(
                    sessionId = _currentSessionId.value!!,
                    content = userInput,
                    type = "text",
                    onThinking = { thinking ->
                        latestThinking = thinking
                        updateThinkingMessage()
                    },
                    onContent = { content ->
                        aiContent += content
                        updateThinkingMessage()
                    },
                    onComplete = { messageId, sessionId, sender, modelId ->
                        finalMessageId = messageId
                        
                        // 更新最终的AI消息
                        val currentMessages = _messages.value.toMutableList()
                        val index = currentMessages.indexOfFirst { it.id == tempAiMessageId }
                        if (index != -1) {
                            currentMessages[index] = Message(
                                id = finalMessageId,
                                content = aiContent,
                                timestamp = timeFormat.format(Date()),
                                isUser = false
                            )
                            _messages.value = currentMessages
                        }
                    }
                )
            } catch (e: Exception) {
                // 处理错误情况
                android.util.Log.e("ChatViewModel", "发送消息失败", e)
                _errorMessage.value = "发送消息失败: ${e.message ?: "未知错误"}"
                
                // 更新临时消息为错误状态
                val currentMessages = _messages.value.toMutableList()
                val index = currentMessages.indexOfFirst { it.id == tempAiMessageId }
                if (index != -1) {
                    currentMessages[index] = currentMessages[index].copy(
                        content = "抱歉，消息发送失败，请稍后重试。",
                        thinkingProcess = null
                    )
                    _messages.value = currentMessages
                }
            }
        }
    }

    fun toggleDrawer() {
        _isDrawerOpen.value = !_isDrawerOpen.value
    }

    fun showEditSessionDialog(session: ChatSession) {
        _sessionToEdit.value = session
        _newSessionTitle.value = session.title
        _showEditDialog.value = true
    }

    fun hideEditSessionDialog() {
        _showEditDialog.value = false
    }

    fun updateSessionTitle() {
        val session = _sessionToEdit.value ?: return
        if (_newSessionTitle.value.isBlank()) return

        // 显示加载状态或禁用按钮等UI处理可以在这里添加
        
        viewModelScope.launch {
            try {
                // 调用仓库方法更新会话标题
                val result = chatSessionRepository.updateSessionTitle(session.id, _newSessionTitle.value)
                
                result.fold(
                    onSuccess = {
                        // 更新本地会话列表
                        val updatedSession = session.copy(title = _newSessionTitle.value)
                        _sessions.value = _sessions.value.map {
                            if (it.id == session.id) updatedSession else it
                        }
                        _showEditDialog.value = false
                    },
                    onFailure = { exception ->
                        // 显示错误消息
                        _errorMessage.value = exception.message ?: "更新会话标题失败"
                    }
                )
            } catch (e: Exception) {
                _errorMessage.value = "更新会话标题失败: ${e.message}"
            }
        }
    }

    fun updateNewSessionTitle(title: String) {
        _newSessionTitle.value = title
    }

    fun showDeleteSessionDialog(session: ChatSession) {
        _sessionToEdit.value = session
        _showDeleteDialog.value = true
    }

    fun hideDeleteSessionDialog() {
        _showDeleteDialog.value = false
    }

    fun deleteSession() {
        val session = _sessionToEdit.value ?: return
        
        viewModelScope.launch {
            try {
                val result = chatSessionRepository.deleteSession(session.id)
                if (result.isSuccess) {
                    // 删除成功，更新本地会话列表
                    _sessions.value = _sessions.value.filter { it.id != session.id }
                    
                    // 如果删除的是当前会话，切换到其他会话
                    if (_currentSessionId.value == session.id) {
                        _currentSessionId.value = _sessions.value.firstOrNull()?.id
                        _currentSessionId.value?.let { loadMessages(it) } ?: run { _messages.value = emptyList() }
                    }
                } else {
                    // 处理错误情况，添加错误日志和提示
                    val errorMsg = result.exceptionOrNull()?.message ?: "删除会话失败"
                    android.util.Log.e("ChatViewModel", "删除会话失败: $errorMsg")
                    _errorMessage.value = "删除会话失败: $errorMsg"
                }
            } catch (e: Exception) {
                // 处理异常情况，添加异常日志和提示
                android.util.Log.e("ChatViewModel", "删除会话异常", e)
                _errorMessage.value = "删除会话失败: ${e.message ?: "未知错误"}"
            } finally {
                // 无论成功失败，都关闭删除对话框
                _showDeleteDialog.value = false
            }
        }
    }

    fun logout() {
        viewModelScope.launch {
            preferencesManager.clearToken()
        }
    }

    fun selectSession(sessionId: String) {
        _currentSessionId.value = sessionId
        loadMessages(sessionId)
        _isDrawerOpen.value = false
    }
    
    // 添加清除错误消息的方法
    fun clearErrorMessage() {
        _errorMessage.value = null
    }
}